package com.dk.nfc.DeviceManager;

import android.nfc.tech.NfcB;
import android.util.Log;

import com.DKCloudID.crypt.MsgCrypt;
import com.dk.log.DKLog;
import com.dk.nfc.Card.SamVIdCard;
import com.dk.nfc.DKCloudID.IDCard;
import com.dk.nfc.DKCloudID.IDCardData;
import com.dk.nfc.Exception.CardNoResponseException;
import com.dk.nfc.Exception.DKCloudIDException;

import java.io.IOException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class DeviceManager {
    private final static String TAG = "DeviceManager";

    public MsgCrypt msgCrypt;
    private DeviceManagerCallback mDeviceManagerCallback = null;
    private static final Semaphore semaphore = new Semaphore(1);

    public DeviceManager(MsgCrypt msgCrypt) {
        this.msgCrypt = msgCrypt;
    }

    public void setCallBack(DeviceManagerCallback callBack) {
        mDeviceManagerCallback = callBack;
    }

    public void onFinCard(NfcB nfcB) {
        SamVIdCard samVIdCard = new SamVIdCard(DeviceManager.this, nfcB);

        //如果上次解析还未完成，则抛弃新刷的身份证
        try {
            if ( !semaphore.tryAcquire(0, TimeUnit.MILLISECONDS) ) {
                DKLog.d(TAG, "上次解析还未完成，抛弃本次刷的身份证");
                return;
            }
        } catch (InterruptedException e) {
            DKLog.e(TAG, e.getMessage());
            DKLog.e(TAG, e.getStackTrace());
            DKLog.d(TAG, "上次解析还未完成，抛弃本次刷的身份证");
            return;
        }

        if (mDeviceManagerCallback != null) {
            mDeviceManagerCallback.onReceiveSamVIdStart(null);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    IDCardData idCardData = startDkcloudid(samVIdCard);
                    if ( (idCardData != null) && (mDeviceManagerCallback != null) ) {
                        if ( idCardData.PhotoBmp == null ) {
                            mDeviceManagerCallback.onReceiveSamVIdException("明文数据异常");
                        }
                        else {
                            mDeviceManagerCallback.onReceiveIDCardData(idCardData);
                        }
                    }
                }catch (Exception e) {
                    DKLog.e(TAG, e.getMessage());
                    DKLog.e(TAG, e.getStackTrace());
                    if (mDeviceManagerCallback != null) {
                        mDeviceManagerCallback.onReceiveSamVIdException(e.getMessage());
                    }
                }

                semaphore.release();
            }
        }).start();
    }

    //云解码流程
    private synchronized IDCardData startDkcloudid(SamVIdCard card) {
        if (card == null) {
            DKLog.e(TAG, "未找到身份证");
            if (mDeviceManagerCallback != null) {
                mDeviceManagerCallback.onReceiveSamVIdException("未找到身份证");
            }
            return null;
        }

        try {
            /**
             * 获取身份证数据，带进度回调，如果不需要进度回调可以去掉进度回调参数或者传入null
             * 注意：此方法为同步阻塞方式，需要一定时间才能返回身份证数据，期间身份证不能离开读卡器！
             */
            return IDCard.getInstance().getIDCardData(card, 5, new IDCard.onReceiveScheduleListener() {
                @Override
                public void onReceiveSchedule(int rate) {  //读取进度回调
                    if (mDeviceManagerCallback != null) {
                        mDeviceManagerCallback.onReceiveSamVIdSchedule(rate);
                    }
                }
            });
        } catch (DKCloudIDException e) {   //服务器返回异常，重复5次解析
//            e.printStackTrace();
            if (mDeviceManagerCallback != null) {
                mDeviceManagerCallback.onReceiveSamVIdException(e.getMessage());
            }
        } catch (CardNoResponseException e) {    //卡片读取异常，直接退出，需要重新读卡
//            e.printStackTrace();
            if (mDeviceManagerCallback != null) {
                mDeviceManagerCallback.onReceiveSamVIdException(e.getMessage());
            }
        }

        return null;
    }
}
